<template>
  <scroll-view scroll-y class="swiper-scroll">
    <!-- <u-tabs v-if="examType == config.examTypeDict[4]" bar-height="6" bar-width="40" active-color="#03BEFF" :list="list" :is-scroll="false" :current="current" @change="change"></u-tabs> -->
    <u-subsection
      active-color="#03BEFF"
      bgColor="#ECF3FC"
      :list="list"
      v-if="examType == config.examTypeDict[4]"
      :current="curNow"
      @change="sectionChange"
    ></u-subsection>
    <!--   <u-tabs v-if="examType == config.examTypeDict[5]" bar-height="6" bar-width="40" active-color="#03BEFF" :list="listScence" :is-scroll="false" :current="currentScence" @change="changeScence"></u-tabs> -->
    <u-subsection
      active-color="#03BEFF"
      bgColor="#ECF3FC"
      :list="listScence"
      v-if="examType == config.examTypeDict[5]"
      :currentScence="1"
    ></u-subsection>

    <view class="errorList" v-if="examType == config.examTypeDict[4]">
      <view class="errorList_zoom">
        <view class="text"> 错题总数： </view>
      </view>
      <u-line-progress
        :striped-active="true"
        active-color="#82B2FF"
        :percent="70"
      ></u-line-progress>
      <view class="icon" @click="resetError" v-if="curNow === 1">
        <u-icon name="trash-fill" class="trash-fill"></u-icon>
      </view>
    </view>
    <!-- 题干 -->
    <view class="title">
      <!-- 题标顺序不用examIndex是因为其需要计算，在swiper切换完成后才能更新视图 -->
      <!-- 因为此处题标顺序需要预加载前后页题标顺序，故使用父组件索引传值idx -->
      <text class="title-index">{{ idx + 1 }}.</text>
      <view class="title-content">
        <view class="paper-type-tag">
          {{ config.paperTypeDict[curItem.questionType] }}
          {{
            examType == config.examTypeDict[3]
              ? "（出错率：70%）"
              : examType == config.examTypeDict[4]
              ? "（错误率：80%）"
              : ""
          }}
        </view>
        <!-- <rich-text class="rich-text" :nodes="curItem.exam_title"></rich-text> -->
        <mp-html class="rich-text" :content="curItem.titleContent" />
        <u-tag
          text="还不大会"
          type="error"
          v-if="curItem.statusBtn === 'notKnow'"
        />
        <u-tag
          text="理解一点"
          type="success"
          v-if="curItem.statusBtn === 'iGetIt'"
        />
        <u-tag
          text="我熟悉了"
          type="warning"
          v-if="curItem.statusBtn === 'notFamiliar'"
        />
        <u-tag
          text="完全掌握"
          type="primary"
          v-if="curItem.statusBtn === 'mastered'"
        />
      </view>
    </view>
    <!-- 选项 -->
    <view class="options">
      <exam-options :paper-item="curItem" @change="onSelect"></exam-options>
    </view>
    <view class="scence" v-if="examType == this.config.examTypeDict[6]">
      背题记录 :
      <view class="scence_1">
        <u-tag text="2024-10-02 " type="success" />
      </view>
      <view class="scence_2">
        <u-tag text="2024-12-02 " type="success" />
      </view>
    </view>

    <view class="scenceAssociation" v-if="associated">
      联想词 :
      <view
        class="scenceAssociation-text"
        v-for="(item, index) in curItem.tags.filter(
          (tag) => tag === aIAssociate || curItem.tags.indexOf(tag) < 3
        )"
        :key="item.id"
      >
        <u-tag :text="item" :type="item === aIAssociate ? 'success' : 'info'" />
      </view>
    </view>
    <u-button
      v-if="
        examType !== config.examTypeDict[2] &&
        examType !== config.examTypeDict[0] &&
        curItem.questionType === 2 &&
        !curItem.submitted
      "
      class="submit_btn"
      type="primary"
      :disabled="curItem.submitted"
      @click="submit"
    >
      提交
    </u-button>
    <!-- 答案 -->
    <view
      class="anwser"
      v-if="
        curItem.submitted && this.examType !== this.config.examTypeDict[0]
      "
    >
      <text>
        正确答案
        <text class="anwser-text">
          {{ correctAnwser }}
        </text>
      </text>
      <text>
        你的答案
        <text :class="[curItem.correct ? 'anwser-correct' : 'anwser-wrong']">
          {{ myAnwser }}
        </text>
      </text>
    </view>
    <!-- 解析 - 背题模式直接显示解析 -->
    <view
      class="analysis"
      v-if="curItem.submitted || examType == config.examTypeDict[0]"
    >
      <view class="analysis-title" v-if="curItem.analyze">标准答案</view>
      <!-- <rich-text :nodes="curItem.analysis"></rich-text> -->
      <mp-html class="analysis-answer" :content="curItem.analyze" />
      <view class="analysis-title" v-if="curItem.analyze">
        <u-image
          width="50rpx"
          height="50rpx"
          src="../../../../static/images/answer.png"
        ></u-image>
        <view> AI解析 </view>
      </view>
      <mp-html
        v-if="curItem.analyze"
        class="analysis-Aianswer"
        :content="highlightedText"
      />
      <view class="analysis-title" v-if="curItem.analyze">
        <u-image
          width="50rpx"
          height="50rpx"
          src="../../../../static/images/answer.png"
        ></u-image>
        <view> 速记小结 </view>
      </view>
      <mp-html
        v-if="curItem.analyze"
        class="analysis-Aisummary"
        :content="curItem.summary ? curItem.summary : '无'"
      />
      <!--      <view class="feedback">
        <text @click="onFeedback(curItem)">{{ config.feedbackText }}</text>
      </view> -->
      <view class="analysis-title">
        <u-image
          width="50rpx"
          height="50rpx"
          src="../../../../static/images/answer.png"
        ></u-image>
        <view> 我的笔记 </view>
        <u-button
          class="edit-note"
          size="mini"
          type="primary"
          plain
          @click="editNote"
          >编辑笔记</u-button
        >
      </view>
      <!-- <u-input v-show="noteEditable" :focus="true" ref="note" class="note" @blur="saveNote" maxlength="30" v-model="curItem.remark" type="textarea" border /> -->
      <mp-html class="note" :content="curItem.remark" />
    </view>
    <view class="control-placeholder"></view>
    <!-- 按钮控制 -->
    <view
      class="control-subbtn"
      v-if="
        examType !== config.examTypeDict[2] &&
        examType !== config.examTypeDict[0]
      "
    >
      <!-- 考试模式最后一题才显示交卷 -->
      <button
        v-if="examType == config.examTypeDict[2] && examIndex == total - 1"
        size="mini"
        type="primary"
        :disabled="curItem.submitted"
        @click="complete"
      >
        交卷
      </button>
      <view
        v-else-if="examType == config.examTypeDict[2] && examIndex < total - 1"
        style="width: 100%; font-size: 12px; text-align: center; opacity: 0.4"
      >
        {{ config.toCompleteText }}
      </view>
    </view>
    <view class="control">
      <view class="control-btn">
        <!-- <u-button size="mini" type="default" :disabled="examIndex == 0" @click="prev">上一题</u-button> -->
      </view>
      <view
        class="control-btn"
        v-if="
          examType == config.examTypeDict[1] ||
          examType == config.examTypeDict[4] ||
          examType == config.examTypeDict[5] ||
          examType == config.examTypeDict[6] ||
          examType == config.examTypeDict[7]
        "
      >
        <u-button
          size="mini"
          type="error"
          @click="updateQuestionStatus('notKnow')"
          >还不大会</u-button
        >
      </view>
      <view
        class="control-btn"
        v-if="
          examType == config.examTypeDict[1] ||
          examType == config.examTypeDict[4] ||
          examType == config.examTypeDict[5] ||
          examType == config.examTypeDict[6] ||
          examType == config.examTypeDict[7]
        "
      >
        <u-button
          size="mini"
          type="success"
          @click="updateQuestionStatus('iGetIt')"
          >理解一点</u-button
        >
      </view>
      <view
        class="control-btn"
        v-if="
          examType == config.examTypeDict[1] ||
          examType == config.examTypeDict[4] ||
          examType == config.examTypeDict[5] ||
          examType == config.examTypeDict[6] ||
          examType == config.examTypeDict[7]
        "
      >
        <u-button
          size="mini"
          type="warning"
          @click="updateQuestionStatus('notFamiliar')"
          >我熟悉了</u-button
        >
      </view>
      <view
        class="control-btn"
        v-if="
          examType == config.examTypeDict[1] ||
          examType == config.examTypeDict[4] ||
          examType == config.examTypeDict[5] ||
          examType == config.examTypeDict[6] ||
          examType == config.examTypeDict[7]
        "
      >
        <u-button
          size="mini"
          type="primary"
          @click="updateQuestionStatus('mastered')"
          >完全掌握</u-button
        >
      </view>
      <view class="control-btn">
        <!-- <u-button size="mini" type="default" :disabled="examIndex == total - 1" @click="next">下一题</u-button> -->
      </view>
    </view>
    <u-modal
      :mask-close-able="true"
      v-model="handleError"
      :show-cancel-button="true"
      title="清空错题本全部错题"
    >
      <view class="slot-content">
        <view class="container_popup_text"> 确定清空吗？ </view>
      </view>
    </u-modal>
    <!-- 编辑笔记 -->
    <u-modal
      :mask-close-able="true"
      v-model="showEditModal"
      :show-cancel-button="true"
      @confirm="confirm"
      title="编辑笔记"
    >
      <view class="slot-content">
        <u-input
          class="note"
          maxlength="300"
          v-model="value"
          type="textarea"
          border
        />
      </view>
    </u-modal>
  </scroll-view>
</template>

<script>
import ExamOptions from "./exam-options.vue";
import config from "@/uni_modules/sv-exam-plus/config.js";
import store from "@/uni_modules/sv-exam-plus/store/index.js";
import { supermemo } from "supermemo";
import { createNote, updateNote } from "@/api/addPaper/addpaper.js";

export default {
  components: {
    ExamOptions,
  },
  props: {
    // 当前题目
    curItem: {
      type: Object,
      default: () => {},
    },
    // 题标顺序
    idx: {
      type: Number,
      default: 0,
    },
    typeL: {
      type: String,
    },
    examPaperId: {
      type: Number,
    },
  },
  data() {
    return {
      curNow: 0,
      handleError: false,
      config, // 兼容写法，需要先声明否则报错
      list: [
        {
          name: " 考友易错（34 ）",
        },
        {
          name: "个人易错（17）",
        },
      ],

      listScence: [
        {
          name: " 理论（3）",
        },
        {
          name: "实操（4）",
        },
        {
          name: "风险（2）",
        },
        {
          name: "其他（1）",
        },
      ],
      current: 0,
      currentScence: 0,
      nextcurIndex: "",
      isFlashing: false, // 是否处于闪回页面标志
      noteEditable: false,
      showEditModal: false,
      value: "",
    };
  },
  computed: {
    highlightedText() {
      const correctAnswers = this.curItem.correctArray;
      let keywords = this.curItem.optionsItems
        .filter((item) => correctAnswers.includes(item.prefix))
        .map((item) => item.content)
        .join(""); // 将关键词拼接成一个字符串
      if (keywords.includes("、")) {
        keywords = keywords.split(/、|，/); // 使用中文逗号拆分关键词
      } else {
        keywords = this.curItem.optionsItems
          .filter((item) => correctAnswers.includes(item.prefix))
          .map((item) => item.content); // 如果没有分隔符，则将整个字符串作为单个关键词
      }
      const regex = new RegExp(keywords.join("|"), "g");
      if (!this.curItem.aiAnalyze) return;
      return this.curItem.aiAnalyze.replace(
        regex,
        (match) => `<b style="color: #477DFD;">${match}</b>`
      );
    },

    examData: {
      set(newData) {
        store.commit("updateData", newData);
      },
      get() {
        return store.state.examData;
      },
    },
    examType: {
      set(newType) {
        store.commit("updateType", newType);
      },
      get() {
        return store.state.examType;
      },
    },
    associated: {
      set(newType) {
        store.commit("updateAIAssociate", newType);
      },
      get() {
        return store.state.associated;
      },
    },
    examIndex: {
      set(newIndex) {
        // store.commit("updateIndex", newIndex);
      },
      get() {
        return store.state.examIndex;
      },
    },
    aIAssociate: {
      set(newIndex) {
        store.commit("updateaIAssociate", newIndex);
      },
      get() {
        return store.state.aIAssociate;
      },
    },
    currentQuestionIndex: {
      set(currentQuestionIndex) {
        store.commit("updateCurrentQuestionIndex", currentQuestionIndex);
      },
      get() {
        return store.state.currentQuestionIndex;
      },
    },
    count: {
      set(count) {
        store.commit("updateCount", count);
      },
      get() {
        return store.state.count;
      },
    },
    total() {
      return store.state.examData?.length || 0;
    },
    correctAnwser() {
      return this.curItem.correctArray?.sort()?.toString() || "--";
    },
    myAnwser() {
      return (
        this.curItem.selected?.sort()?.toString() ||
        this.curItem.customArray?.sort()?.toString()
      );
    },
  },
  // watch: {
  //   curItem: {
  //     handler(newData) {
  //       this.curItem = newData;
  //     },
  //     immediate: true,
  //   },
  // },
  created() {
    this.init();
    // 监听交卷
    this.onCompleted();
  },
  methods: {
    //保留联想词

    // 还不大会
    practice(flashcard, status) {
      const gradeMap = {
        notKnow: 3,
        iGetIt: 3,
        notFamiliar: 4,
        mastered: 5,
      };
      const { interval, repetition, efactor } = supermemo(
        flashcard,
        gradeMap[status]
      );

      let dueIndex = 0;
      if (this.isFlashing) {
        dueIndex = flashcard.dueIndex || 0;
      }
      const dueIndexRatio = status === 'mastered' ? 0 : 5;
      dueIndex += interval * dueIndexRatio;
      return { ...flashcard, interval, repetition, efactor, dueIndex };
    },
    updateQuestionStatus(status) {
      // 1.赋值状态
      this.$set(this.curItem, 'statusBtn', status)
      console.log(this.curItem, this.curItem)
      // this.curItem.selected = [];
      
      // 添加闪回逻辑
      let flashcard = {
        interval: 0,
        repetition: 0,
        efactor: 2.5,
        ...this.curItem,
      };
      flashcard = this.practice(flashcard, status);
      const data = {
        ...this.curItem,
        ...flashcard,
      };
      this.examData[this.examIndex] = data;
      
      this.handleNext()
    },
    sectionChange(index) {
      this.curNow = index;
    },
    //删除错题
    resetError() {
      this.handleError = true;
    },
    change(index) {
      this.current = index;
    },
    changeScence(index) {
      this.currentScence = index;
    },
    async init() {},
    prev() {
      // const curIndex = this.examIndex <= 0 ? 0 : this.examIndex - 1
      // store.commit('updateIndex', curIndex)
      this.$emit("prev");
    },
    next() {
      this.$emit("next");
    },
    handleNext() {
      const { submitted, statusBtn } = this.examData[this.examIndex]
      if (submitted && statusBtn) {
        this.next()
      }
    },
    submit() {
      // 直接赋值在vue2环境下会丢失响应式
      this.$set(this.curItem, "submitted", true);
      this.handleNext()

      const findex = this.examData.findIndex(
        (item) => item.questionId == this.curItem.questionId
      );
      console.log(findex, "findex");
      // #ifdef VUE2
      // #ifdef MP-WEIXIN
      // 在vue2环境下的微信小程序响应式会丢失，需要手动设置
      store.commit("updateDataElement", {
        index: findex,
        key: "submitted",
        value: true,
      });
      // #endif
      // #endif
      const handleSubmit = {
        selected: this.curItem.selected || [],
        correct: this.curItem.correct || false,
        paper: this.curItem,
        index: findex,
      };
      // 跨组件通信 - 提交
      uni.$emit("e-exam-paper-item-submit", handleSubmit);
    },
    onSelect(e) {
      // 直接赋值在vue2环境下会丢失响应式
      this.$set(this.curItem, "selected", e.selected);
      this.$set(this.curItem, "correct", e.correct);
      // #ifdef VUE2
      // #ifdef MP-WEIXIN
      // 在vue2环境下的微信小程序响应式会丢失，需要手动设置
      const findex = this.examData.findIndex(
        (item) => item.questionId == this.curItem.questionId
      );
      store.commit("updateDataElement", {
        index: findex,
        key: "selected",
        value: e.selected,
      });
      store.commit("updateDataElement", {
        index: findex,
        key: "correct",
        value: e.correct,
      });
      // #endif
      // #endif
    },
    /**
     * 纠错反馈
     */
    onFeedback(e) {
      uni.$emit("e-exam-paper-item-feedback", e);
    },
    // 交卷
    complete() {
      uni.showModal({
        title: "交卷",
        content: "确认检查无误后交卷吗？",
        showCancel: true,
        success: ({ confirm }) => {
          if (confirm) {
            // 跨组件通信 - 交卷
            uni.$emit("e-exam-paper-complete", this.examData);
          }
        },
      });
    },
    // 监听交卷
    onCompleted() {
      // exam模式开启交卷监听
      if (this.examType == this.config.examTypeDict[2]) {
        uni.$on("e-exam-paper-complete", () => {
          // 唤醒提交
          this.submit();
        });
      }
    },
    editNote() {
      this.value = this.curItem.remark;
      this.showEditModal = true;
    },
    confirm() {
      if (this.curItem.remarked) {
        this.updateNote(this.value);
      } else {
        this.saveNote(this.value);
      }
    },
    saveNote(v) {
      this.showEditModal = false;
      createNote({
        examPaperId: this.examPaperId,
        questionId: this.curItem.questionId,
        remark: v,
      }).then(() => {
        this.curItem.remark = v;
      });
    },
    updateNote(v) {
      this.showEditModal = false;
      updateNote({
        id: this.curItem.remarkId,
        examPaperId: this.examPaperId,
        questionId: this.curItem.questionId,
        remark: v,
      }).then(() => {
        this.curItem.remark = v;
      });
    },
  },
};
</script>

<style lang="scss">
.swiper-scroll {
  height: 100%;
  padding-bottom: var(--card-header-height);

  .errorList {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--paper-unit-12);

    .errorList_zoom {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .text {
        font-size: 25rpx;
        color: darkgray;
      }
    }

    .u-progress {
      width: 60%;
      height: 20rpx !important;
    }

    .trash-fill {
      color: #82b2ff;
    }
  }

  .title {
    padding: var(--paper-unit-12);
    box-sizing: border-box;
    display: flex;

    .title-index {
      line-height: 1.6;
      margin-right: 24rpx;
    }

    .title-content {
      flex: 1;

      .paper-type-tag {
        background-color: var(--primary-color);
        margin-right: var(--paper-unit-12);
        padding: 4rpx 8rpx;
        border-radius: 8rpx;
        color: #ffffff;
        font-size: 12px;
        box-sizing: border-box;
        float: left;
        position: relative;
        top: 6rpx;
      }

      .rich-text {
        display: inline;
        line-height: 1.6;
      }
    }
  }

  .options {
    padding: var(--paper-unit-12);
    box-sizing: border-box;
  }

  .scence {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: var(--paper-unit-12);

    .scence_1 {
      margin: 0 20rpx;
    }
  }

  .scenceAssociation {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: var(--paper-unit-12);

    .scenceAssociation-text {
      display: flex;
      flex-wrap: wrap;

      .u-tag {
        width: auto;
        margin: 10rpx;
      }
    }
  }

  .anwser {
    margin: var(--paper-unit-12);
    padding: var(--paper-unit-12);
    box-sizing: border-box;
    background-color: #f4f5f7;
    border-radius: calc(#{var(--paper-unit-12)} / 2);

    .anwser-text,
    .anwser-correct {
      font-weight: 700;
      color: var(--success-color);
      margin: 0 24rpx;
    }

    .anwser-wrong {
      font-weight: 700;
      color: var(--error-color);
      margin: 0 24rpx;
    }
  }

  .analysis {
    margin: var(--paper-unit-12);
    box-sizing: border-box;
    background-color: #fff;
    border-radius: calc(#{var(--paper-unit-12)} / 2);

    .analysis-title {
      display: flex;
      margin: 20rpx 0;
      font-weight: 700;
      margin-top: 50rpx;
      .edit-note {
        margin-right: 0;
      }
    }

    .analysis-answer {
      color: #787878;
    }

    .analysis-Aianswer {
      background-color: #ebf0ff;
      padding: 20rpx;
      border-radius: 10rpx;
    }

    .analysis-Aisummary {
      background-color: #ebf9ff;
      padding: 20rpx;
      border-radius: 10rpx;
    }

    .feedback {
      font-size: 12px;
      margin-top: var(--paper-unit-12);
      opacity: 0.6;
      text-align: right;
    }
  }

  .control-subbtn {
    position: fixed;
    bottom: 100rpx;
    right: 10rpx;
    z-index: 1;
  }

  .control {
    width: 100%;
    height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0;
    z-index: 1;

    .control-btn {
    }
  }

  .control-placeholder {
    width: 100%;
    height: 100rpx;
  }
}

.container_popup_text {
  text-align: center;
  margin: 30rpx 0;
}

.submit_btn {
  margin: auto;
  width: 200rpx;
}
</style>
